<template>
	<!-- prop是自定义的数据字段名，要与chang后的保持一致，h2cRender是renderjs的module名称 -->
	<view class="sp-html2canvas-render" :prop="domId" :change:prop="h2cRender.watchDomId">
		<slot></slot>
		<slot name="control" :h2cRender="h2cRender">
			<!-- <button class="exp-btn" size="mini" @click="h2cRender.renderDom">保存到相册</button> -->
		</slot>
	</view>
</template>

<script>
	export default {
		props: {
			// 要渲染dom的id
			domId: {
				type: String,
				default: ''
			}
		},
 
		data() {
			return {
				// #ifdef VUE2
				// #ifdef APP
				// 只有在Vue2的APP真机中需要先声明h2cRender，否则会报错，若未报错建议删除此处代码
				h2cRender: null
				// #endif
				// #endif
			}
		},
		methods: {
			renderOver(e) {
				// 监听渲染生成完成
				this.$emit('renderOver', e)
			},
			 
		}
	}
</script>

<!-- renderjs目前仅支持内联使用 -->
<script module="h2cRender" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		data() {
			return {
				domIdValue: ''
			}
		},
		methods: {
			
		 
			async renderDom() {
				// app无法通过传参获取domId,也无法直接获取到script中data或props数据
				// 必须通过特定的监听方式,与script通信,获取其data
				try {
					const el = document.getElementById(this.domIdValue);
					const canvas = await html2canvas(el, {
						width: el.offsetWidth,
						height: el.offsetHeight,
						x: 0,
						y: 0,
						logging: true,
						useCORS: true,
						allowTaint: true,
						scale: 2, // 2倍，增强清晰度
					});
					const base64 = canvas.toDataURL('image/jpeg', 1);
					this.$ownerInstance.callMethod('renderOver', base64);
					// this.$emit("save",base64)
				} catch (err) {
					// this.$emit("save",err.message)
					console.log('==== err :', err.message);
				}
			},
			// 监听方式,与script通信,获取其data
			watchDomId(newValue, oldValue, ownerInstance, instance) {
				this.domIdValue = newValue
			},
		}
	}
</script>

<style>
	.sp-html2canvas-render {
		position: relative;
	}

	.exp-btn {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
		line-height: unset;
		padding: 12rpx;
	}
</style>